package com.jxy.voice.facotry;

import com.jxy.voice.enums.TtsTypeEnum;
import com.jxy.voice.strategy.TtsStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName TtsFactory
 * @Description 合成策略工厂
 * @Author zheng
 * @Date 2022/10/13 15:00
 * @Version 1.0
 **/
@Slf4j
public class TtsStrategyFactory {
    /**
     * 合成策略缓存
     */
    private static final ConcurrentHashMap<String, TtsStrategy> TTS_STRATEGY_MAP = new ConcurrentHashMap<>();

    /**
     * @return com.jxy.voice.strategy.TtsStrategy
     * @Description 根据类型获取合成策略
     * @Date 2022/10/13 15:35
     * @Param [type] [声码器类型]
     **/
    public static TtsStrategy getTtsStrategy(String type) {
        TtsStrategy ttsStrategy = TTS_STRATEGY_MAP.get("type");
        if (ttsStrategy != null) {
            return ttsStrategy;
        }
        //合成策略全类名
        String ttsClassFullName = TtsTypeEnum.getTtsClassFullName(type);
        if (StringUtils.isBlank(ttsClassFullName)) {
            log.error("get ttsClassFullName error，type is:{},please check!", type);
            throw new IllegalArgumentException(String.format("未知的合成策略类型：%s", type));
        }
        //反射生成对应的类
        Class<?> clazz = null;
        try {
            clazz = Class.forName(ttsClassFullName);
            ttsStrategy = (TtsStrategy) clazz.newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            log.error("get TtsStrategy failed.{} ", e.toString());
            throw new RuntimeException(e);
        }
        TTS_STRATEGY_MAP.put(type, ttsStrategy);
        return ttsStrategy;
    }
}
